package com.blog.quartz;

import com.blog.config.ScheduleConstants;
import com.blog.entity.SysJob;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;

import java.util.Date;

/**
 * @author cgx
 * @Date 2022/1/11 11:07
 */
public abstract class AbstractQuartzJob implements Job {


    private static final Logger log = LoggerFactory.getLogger(AbstractQuartzJob.class);



    /**
     * 线程本地变量
     */
    private static ThreadLocal<Date> threadLocal = new ThreadLocal<>();

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {

        SysJob sysJob = new SysJob();
        BeanUtils.copyProperties(context.getMergedJobDataMap().get(ScheduleConstants.TASK_PROPERTIES),sysJob);
        
        //执行前创建线程
        jobRunBefore(sysJob);
        if (sysJob != null){
            try {
                doExecute(context, sysJob);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        jobRunAfter(sysJob);
    }

    protected void jobRunAfter(SysJob sysJob) {
        Date startTime = threadLocal.get();
        threadLocal.remove();
        log.info("任务名： "+sysJob.getJobName()+" 成功执行");
        Date endTime = new Date();
        long time = endTime.getTime() - startTime.getTime();
        log.info("耗时： "+time+" 毫秒");
        log.info("=================>");
    }

    protected void jobRunBefore(SysJob sysJob) {
        threadLocal.set(new Date());
        log.info("=================>");
        log.info("任务名： "+sysJob.getJobName()+" 开始执行");
    }

    /**
     * 执行方法，由子类重载
     *
     * @param context 工作执行上下文对象
     * @param sysJob 系统计划任务
     * @throws Exception 执行过程中的异常
     */
    protected abstract void doExecute(JobExecutionContext context, SysJob sysJob) throws Exception;
}
